package com.ant.androidBuddy;

import java.io.*;
import java.lang.reflect.Field;

import android.app.*;
import android.content.*;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

public class AnimationActivity extends Activity{

	//the code in the text box
	public static String code="";

	//represents no tutorial
	public static final int NO_TUTORIAL=-1;


	//the stage in the tutorial
	public int tutorialStage=NO_TUTORIAL;

	//the array of text to show for the tutorial
	public String[] tutArray;

	//the array of code to show for the tutorial
	public String[] tutCodeArray;

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.animation);
		Intent in =  getIntent();
		//if new mode
		if(in.getStringExtra("new") != null && in.getStringExtra("new").equals("start_new")){
			code = "";
		}
		//if tutorial  mode
		else{
			if(in.getStringExtra("tutorial") != null && in.getStringExtra("tutorial").equals("start_tut")){
				//set stuff
				code = "";
				tutorialStage=0;
				tutArray=getResources().getStringArray(R.array.tut_array);
				tutCodeArray=getResources().getStringArray(R.array.tut_code_array);
				//prevent landscape mode (prevent loss of information when mode changes)
				setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			}
			else{
				//get any code that was passed in the intent
				String saved=in.getStringExtra("savedtxt");
				if(saved!=null){
					code=saved;
				}
			}
		}
		//set the text to the saved code
		((TextView)findViewById(R.id.cmd)).setText(code);
		//add the up button to the action bar
		ActionBar actionBar=getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		//force overflow on devices with physical menu key
	    try {
	        ViewConfiguration config = ViewConfiguration.get(this);
	        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
	        if(menuKeyField != null) {
	            menuKeyField.setAccessible(true);
	            menuKeyField.setBoolean(config, false);
	        }
	    } catch (Exception ex) {
	        // Ignore
	    }
		//save any code in the text box
		getTextContent();
		//show the first tutorial if relevant
		nextTutorial();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//add the action buttons
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.animation_menu, menu);
		return true;
	}

	@Override
	//when an action button is pressed
	public boolean onOptionsItemSelected(MenuItem item) 
	{    
		//save the code in the text box
		getTextContent();
		//switch by the item id
		switch (item.getItemId()) 
		{        
		case android.R.id.home:{
			//go home
			Intent intent = new Intent(this, AndroidBuddyActivity.class);            
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);            
			return true;
		}
		case R.id.btn_run:{
			//run the animation
			String cmd = ((TextView)findViewById(R.id.cmd)).getText().toString();
			Intent in =  getIntent();
			//if tutorial  mode
			if(cmd.length() == 0){
				((TextView)findViewById(R.id.cmd)).setText("");
				showAlert(getString(R.string.no_input));
				return true;
			}
			parseText();
			return true;
		}
		case R.id.btn_save:{
			//go to the save activity
			Intent intent = new Intent(AnimationActivity.this, SaveFileActivity.class);
			//add the text to be saved
			intent.putExtra("cmd", code);
			startActivity(intent);
			return true;
		}
		case R.id.btn_open:{
			//go to the open activity
			Intent intent = new Intent(AnimationActivity.this, OpenFileActivity.class); 
			startActivity(intent);
			return true;
		}
		case R.id.btn_ref:{
			//show the reference text
			showAlert(getString(R.string.commands));
			return true;
		}
		case R.id.btn_reset:{
			//reset the text
			resetText();
			return true;
		}
		default:   {  
			//this should never happen
			return super.onOptionsItemSelected(item);    
		}
		}
	}

	//goes to the next tutorial stage
	public void nextTutorial(){
		//if the tutorial is not active
		if(tutorialStage==NO_TUTORIAL){
			//do nothing
			return;
		}
		showAlert(tutArray[tutorialStage]+":\n\n"+tutCodeArray[tutorialStage]);
		((TextView)findViewById(R.id.cmd)).setHint(tutCodeArray[tutorialStage]);
		//go to the next stage
		tutorialStage++;
		
		//if at the end of the tutorial
		if(tutorialStage==tutArray.length){
			tutorialStage=NO_TUTORIAL;
			tutArray=null;
			tutCodeArray=null;
			((EditText)findViewById(R.id.cmd)).setHint(R.string.textHint);
			//prevent landscape mode (prevent loss of information when mode changes)
			setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_USER);
		}
	}

	//resets the code in the text box
	public void resetText(){
		//set the text box
		((EditText)findViewById(R.id.cmd)).setText("");
		//update the code variable
		getTextContent();
	}

	//starts an animation
	public void parseText(){
		if(Interpreter.running){
			showAlert(getString(R.string.running));
			return;
		}
		//the framelayout to contain the androids must be passed to the android class statically
		AndroidCharacter.layout=(FrameLayout)findViewById(R.id.androidcontainer);
		//the android also needs the context
		AndroidCharacter.context=getApplicationContext();
		//change it to a bufferedreader
		BufferedReader reader=new BufferedReader(new InputStreamReader(new ByteArrayInputStream(code.getBytes())));
		//run it
		Interpreter.start(reader,this);
	}

	//shows an alert
	public void showAlert(String message){
		//the dialog builder
		final AlertDialog.Builder alertBuilder=new AlertDialog.Builder(this);
		//set the message
		alertBuilder.setMessage(message)
		//add a button that dismisses the message
		.setPositiveButton(R.string.OK_button, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		//create the alert
		AlertDialog alert=alertBuilder.create();
		//show the alert
		alert.show();
	}

	//updates the code variable with the contents of the text box
	public void getTextContent(){
		code=((TextView)findViewById(R.id.cmd)).getText().toString();
	}
}
